package tech.xs.common.util;


import java.util.*;
import java.util.function.Function;

/**
 * 封装通用工具
 *
 * @author 沈家文
 * @since 2023/5/15 15:42
 */
public class FieldUtil {

    public static <R, E> List<R> toList(Collection<E> collection, Function<E, R> field) {
        List<R> res = new ArrayList<>(collection.size());
        for (E item : collection) {
            R v = field.apply(item);
            if (v != null) {
                res.add(v);
            }
        }
        return res;
    }

    public static <R, E> Set<R> toSet(Collection<E> collection, Function<E, R> field) {
        HashSet<R> res = new HashSet<>();
        for (E item : collection) {
            R v = field.apply(item);
            if (v != null) {
                res.add(v);
            }
        }
        return res;
    }

    public static <K, V> Map<K, V> toMap(Collection<V> collection, Function<V, K> field) {
        Map<K, V> res = new HashMap<>();
        for (V item : collection) {
            res.put(field.apply(item), item);
        }
        return res;
    }

}
